<template>
  <div
    class="q-px-xs q-pt-xs define-scroll"
    style="
      width: 100%;
      height: calc(100vh - 28px);
      overflow: hidden;
      display: block;
    "
  >
    <q-card flat>
      <q-tabs
        v-model="tab"
        active-color="purple"
        align="left"
        class="text-black bg-gradation-20deg-e9defa-fbfcdb overflow-hidden q-px-xs"
        dense
        indicator-color="purple"
        inline-label
        stretch
        style="border-radius: 4px; height: 30px"
      >
        <q-btn
          class="bg-gradation-to-top-accbee-e7f0fd"
          size="sm"
          @click="initConfigAndDB"
        >
          <div class="text-no-wrap text-purple" style="font-size: 14px">
            {{ $t('refreshConf') }}
          </div>
        </q-btn>
        <q-separator
          class="q-ma-xs"
          color="bg-gradation-to-top-accbee-e7f0fd"
          size="1px"
          vertical
        />
        <q-tab
          icon="storage"
          :label="$t('dbTab')"
          name="c1"
          style="height: 32px"
        />
        <q-tab
          icon="health_and_safety"
          :label="$t('templateTab')"
          name="c2"
          style="height: 32px"
        />
        <q-tab
          icon="layers"
          :label="$t('templateContentTab')"
          name="c4"
          style="height: 32px"
        />
        <q-tab
          icon="output"
          :label="$t('projectTab')"
          name="c5"
          style="height: 32px"
        />
        <q-tab
          icon="settings"
          :label="$t('settingsTab')"
          name="C6"
          style="height: 32px"
        />
        <q-space />
      </q-tabs>
      <q-tab-panels
        v-model="tab"
        animated
        class="define-scroll"
        style="height: calc(100vh - 72px)"
      >
        <q-tab-panel class="q-pa-none no-scroll" name="c1">
          <q-list>
            <q-bar
              class="bg-gradation-to-top-cd9cf2-f6f3ff q-mt-xs rounded-borders"
            >
              <q-btn
                class="q-ma-xs glass-40 text-white"
                color="green"
                dense
                flat
                icon="add_circle"
                size="10px"
                @click="addDatabaseConfig"
              >
                <q-tooltip delay="700" self="center left">
                  {{ $t('addDb') }}
                </q-tooltip>
              </q-btn>

              <q-btn
                class="q-ma-xs glass-40 text-white"
                color="red"
                dense
                flat
                icon="bug_report"
                size="10px"
                @click="testConnection"
              >
                <q-tooltip delay="700" self="center left"
                  >{{ $t('testDb') }}
                </q-tooltip>
              </q-btn>
              <span
                class="q-mr-lg bg-clip-text bg-gradation-3f51b1-5a55ae"
                style="font-size: 16px"
              >
                {{ $t('dbSettings') }}
              </span>
              <q-space />
              <q-btn
                class="q-my-xs glass-40 text-white"
                dense
                flat
                icon="cloud"
                size="10px"
              >
                <q-tooltip
                  delay="700"
                  class="bg-gradation-3f51b1-5a55ae dyh text-weight-thin text-caption"
                  self="center left"
                >
                  {{ $t('getDbCloud') }}
                </q-tooltip>
              </q-btn>

              <q-btn-dropdown
                class="text-caption text-weight-thin"
                dense
                flat
                size="xs"
              >
                <template v-slot:label>
                  <div class="flex items-center no-wrap">
                    <q-icon name="toc" size="sm" />
                    <div
                      class="text-caption bg-clip-text bg-gradation-120deg-f093fb-f5576c"
                    >
                      {{ $t('DbList') }}
                    </div>
                  </div>
                </template>
                <q-list dense>
                  <q-item
                    v-for="(item, index) in useProjectStore().project
                      .datasource"
                    :key="index"
                    :active="check == index"
                    active-class="bg-teal-1 text-grey-8"
                  >
                    <q-item-section side top>
                      <div class="text-grey-8 q-gutter-xs">
                        <q-btn
                          v-if="!item.id"
                          class="gt-xs"
                          dense
                          flat
                          icon="cloud_upload"
                          round
                          size="12px"
                          @click="uploadDatabase(index)"
                        />
                        <q-btn
                          v-if="item.id"
                          class="gt-xs"
                          dense
                          flat
                          icon="cloud_done"
                          color="green"
                          round
                          size="12px"
                          @click="unUploadDatabase(index)"
                        />
                        <q-btn
                          class="gt-xs"
                          dense
                          flat
                          icon="delete"
                          round
                          size="12px"
                          @click="
                            useProjectStore().project.datasource.splice(
                              index,
                              1
                            )
                          "
                        />
                      </div>
                    </q-item-section>
                    <q-item-section>
                      <q-item-label
                        >{{ item.id ? 'No.' + item.id : '' }}
                        {{ item.nickName + ' ' + item?.host }}
                      </q-item-label>
                      <q-item-label caption>
                        {{ `host:${item.host} database:${item.database}` }}
                      </q-item-label>
                    </q-item-section>

                    <q-item-section side top>
                      <q-radio v-model="check" :val="index" />
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-btn-dropdown>
            </q-bar>
            <q-item class="q-pt-md" dense>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.datasource[check].host"
                  :type="isHost ? 'password' : 'text'"
                  dense
                  style="width: 300px"
                >
                  <template v-slot:append>
                    <q-icon
                      :name="isHost ? 'visibility_off' : 'visibility'"
                      class="cursor-pointer"
                      @click="isHost = !isHost"
                    />
                  </template>
                </q-input>
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbAddress') }}</q-item-label>
                <q-item-label caption> {{ $t('DbIP') }}</q-item-label>
              </q-item-section>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.datasource[check].port"
                  dense
                  style="width: 150px"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbPort') }}</q-item-label>
                <q-item-label caption> {{ $t('DbPortDesc') }}</q-item-label>
              </q-item-section>
            </q-item>

            <q-item dense>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.datasource[check].database"
                  dense
                  style="width: 300px"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbName') }}</q-item-label>
                <q-item-label caption> {{ $t('DbNameDesc') }}</q-item-label>
              </q-item-section>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.datasource[check].type"
                  dense
                  style="width: 150px"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbType') }}</q-item-label>
                <q-item-label caption> {{ $t('DbTypeDesc') }}</q-item-label>
              </q-item-section>
            </q-item>
            <q-item dense>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.datasource[check].username"
                  dense
                  style="width: 300px"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbUsername') }}</q-item-label>
              </q-item-section>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.datasource[check].nickName"
                  dense
                  style="width: 150px"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbNickname') }}</q-item-label>
              </q-item-section>
            </q-item>
            <q-item dense>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.datasource[check].password"
                  :type="isPwd ? 'password' : 'text'"
                  dense
                  style="width: 300px"
                >
                  <template v-slot:append>
                    <q-icon
                      :name="isPwd ? 'visibility_off' : 'visibility'"
                      class="cursor-pointer"
                      @click="isPwd = !isPwd"
                    />
                  </template>
                </q-input>
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbPwd') }}</q-item-label>
              </q-item-section>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.datasource[check].save"
                  dense
                  style="width: 150px"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbSave') }}</q-item-label>
              </q-item-section>
            </q-item>

            <q-item class="q-pt-md" dense>
              <q-item-section avatar>
                <q-btn
                  v-if="!useProjectStore().project?.datasource[check]?.id"
                  class="gt-xs"
                  dense
                  flat
                  icon="cloud_upload"
                  round
                  size="12px"
                  @click="uploadDatabase(check)"
                />
                <q-btn
                  v-if="useProjectStore().project.datasource[check].id"
                  class="gt-xs"
                  dense
                  flat
                  icon="cloud_done"
                  color="green"
                  round
                  size="12px"
                  @click="unUploadDatabase(check)"
                />
              </q-item-section>
              <q-item-section>
                <q-item-label>{{ $t('DbCloudSave') }}</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-tab-panel>

        <q-tab-panel class="q-pa-none no-scroll" name="c2">
          <q-list dense>
            <!--            -->
            <q-bar
              class="bg-gradation-to-top-accbee-e7f0fd rounded-borders q-my-xs"
              header
            >
              <span class="q-mr-lg text-body2"> {{ $t('templateList') }} </span>
              <q-space />
              <q-btn
                class="q-py-xs"
                :label="$t('refreshConf')"
                size="sm"
                @click="mineTemplateStore().getMineTemplateStore()"
              />
            </q-bar>

            <q-splitter
              v-model="splitterModel"
              separator-class="bg-white"
              separator-style="height: 1"
              style="height: calc(100vh - 112px)"
            >
              <template v-slot:before>
                <div
                  class="q-py-xs q-px-xs glass-10 full-height overflow-auto define-scroll rounded-borders"
                >
                  <q-btn
                    v-for="i in mineTemplateStore().mineTemplate"
                    :key="i"
                    :class="
                      i.templateId == templateId
                        ? 'bg-gradation-to-top-9890e3-b1f4cf'
                        : ''
                    "
                    class="rounded-borders flex q-px-md q-mb-xs no-wrap full-width"
                    dense
                    @click="updateEditor(i.templateId)"
                  >
                    {{ i.name }}
                    No:{{ i.templateId }}
                  </q-btn>
                </div>
              </template>

              <template v-slot:after>
                <q-card
                  bordered
                  class="q-ml-xs"
                  flat
                  style="height: calc(100%); width: calc(100% - 4px)"
                >
                  <ql-editor
                    :template-id="templateId"
                    editor-id="templateEditor"
                  />
                </q-card>
              </template>
            </q-splitter>
          </q-list>
        </q-tab-panel>
        <q-tab-panel class="q-pa-sm" name="c4">
          <q-list class="define-scroll">
            <q-item
              v-for="(item, index) in mineTemplateStore().mineTemplate"
              :key="index"
              class="q-pa-none"
              dense
            >
              <q-item-section avatar>
                <q-input
                  v-model="item.data.name"
                  dense
                  :label="$t('templateName')"
                  style="width: 100px"
                />
              </q-item-section>
              <q-item-section avatar>
                <q-input
                  v-model="item.data.componentName"
                  dense
                  :label="$t('templateComponent')"
                  style="width: 100px"
                />
              </q-item-section>
              <q-item-section avatar>
                <q-input
                  v-model="item.data.id"
                  dense
                  :label="$t('templateID')"
                  style="width: 120px"
                >
                </q-input>
              </q-item-section>

              <q-item-section avatar>
                <q-input
                  v-model="item.data.lang"
                  dense
                  :label="$t('templateType')"
                  style="width: 100px"
                />
              </q-item-section>
              <q-btn
                class="q-ml-sm q-ma-sm text-red-6"
                dense
                flat
                icon="delete"
                size="sm"
                @click="mineTemplateList.splice(index, 1)"
              >
                <q-tooltip
                  delay="700"
                  anchor="center left"
                  class="text-green text-bold"
                  >{{ $t('delete') }}
                </q-tooltip>
              </q-btn>
            </q-item>
          </q-list>
        </q-tab-panel>
        <q-tab-panel class="q-pa-none overflow-hidden" name="c5">
          <q-bar
            class="bg-gradation-to-top-cd9cf2-f6f3ff q-mt-xs rounded-borders"
          >
            <q-btn
              class="q-ma-xs glass-40 text-white"
              color="green"
              dense
              flat
              icon="add_circle"
              size="10px"
              @click="addProjectDlg"
            >
              <q-tooltip delay="700" self="center left">{{
                $t('delete')
              }}</q-tooltip>
            </q-btn>
            <span
              class="q-mr-md bg-clip-text bg-gradation-3f51b1-5a55ae"
              style="font-size: 16px"
            >
              {{ $t('projectConf') }}
            </span>
            <q-space />
            <q-btn
              class="q-my-xs glass-40 text-white"
              dense
              flat
              icon="cloud"
              size="10px"
            >
              <q-tooltip
                delay="700"
                class="bg-gradation-3f51b1-5a55ae dyh text-weight-thin text-caption"
                self="center left"
              >
                {{ $t('projectCloud') }}
              </q-tooltip>
            </q-btn>

            <q-btn-dropdown
              class="text-caption text-weight-thin"
              color="purple"
              dense
              size="xs"
              flat
            >
              <template v-slot:label>
                <div
                  class="text-caption justify-center items-center flex no-wrap"
                >
                  <q-icon name="toc" size="xs" />
                  <div>{{ $t('projectList') }}</div>
                </div>
              </template>
              <q-list>
                <q-select
                  v-model="useConfigStore().config.projectName"
                  :options="useConfigStore().config.projects"
                  dense
                  filled
                  style="width: 200px"
                />
              </q-list>
            </q-btn-dropdown>
          </q-bar>
          <q-list>
            <q-item>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.name"
                  dense
                  :label="$t('projectName')"
                  style="width: 200px"
                />
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.out.path"
                  dense
                  :label="$t('projectPath')"
                  style="width: 600px"
                >
                  <template v-slot:append>
                    <q-btn
                      flat
                      icon-right="folder"
                      @click="
                        selectFolder(
                          'useProjectStore().project.out.path',
                          useProjectStore().project.out.path
                        )
                      "
                    >
                    </q-btn>
                  </template>
                  <q-btn
                    class="q-my-xs"
                    dense
                    flat
                    icon="cloud"
                    size="12px"
                    @click="
                      useProjectStore().project.datasource.splice(index, 1)
                    "
                  />
                </q-input>
              </q-item-section>
            </q-item>

            <q-item>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.out.author"
                  dense
                  :label="$t('projectPath')"
                  style="width: 600px"
                >
                </q-input>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.out.parent"
                  dense
                  :label="$t('projectParent')"
                  style="width: 600px"
                >
                </q-input>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section avatar>
                <q-input
                  v-model="useProjectStore().project.out.define"
                  dense
                  :label="$t('projectParent')"
                  style="width: 600px"
                >
                </q-input>
              </q-item-section>
            </q-item>
            <q-item>
              <q-item-section avatar>
                <q-select
                  v-model="useProjectStore().project.out.tables"
                  :options="schemaTableList"
                  dense
                  emit-value
                  :label="$t('projectGenTable')"
                  map-options
                  multiple
                  option-label="name"
                  option-value="name"
                  outlined
                  style="width: 600px"
                >
                  <template
                    v-slot:option="{ itemProps, opt, selected, toggleOption }"
                  >
                    <q-item v-bind="itemProps">
                      <q-item-section>
                        <q-item-label>{{ opt.name }}</q-item-label>
                      </q-item-section>
                      <q-item-section>
                        <q-item-label>{{ opt.nickName }}</q-item-label>
                      </q-item-section>
                      <q-item-section side>
                        <q-toggle
                          :model-value="selected"
                          @update:model-value="toggleOption(opt)"
                        >
                          <q-tooltip delay="700"
                            >{{
                              selected
                                ? $t('projectGenOn')
                                : $t('projectGenOff')
                            }}
                          </q-tooltip>
                        </q-toggle>
                      </q-item-section>
                    </q-item>
                  </template>
                  <template v-slot:append>
                    <q-btn
                      dense
                      icon="clear"
                      size="sm"
                      @click="useProjectStore().project.out.tables = []"
                    />
                  </template>
                </q-select>
              </q-item-section>
            </q-item>
            <q-separator color="orange-4" inset />
            <q-btn
              dense
              class="q-my-xs q-mx-md"
              size="10px"
              icon="add"
              @click="
                useProjectStore().project.mapper.push({
                  path: '',
                  name: '',
                  component: '',
                  componentName: '',
                  templateId: '',
                  outputPath: '',
                  postfix: true,
                })
              "
            >
              <q-tooltip delay="700" class="bg-gradation-to-top-9890e3-b1f4cf">
                <div class="text-weight-bold text-body2">
                  {{ $t('projectTemplateOutPath') }}
                </div>
              </q-tooltip>
            </q-btn>
            <q-list
              class="overflow-auto define-scroll"
              style="height: calc(100vh - 476px)"
            >
              <q-item
                v-for="(item, index) in useProjectStore().project.mapper"
                :key="index"
                dense
              >
                <q-item-section avatar>
                  <q-select
                    v-model="useProjectStore().project.mapper[index]"
                    :options="mineTemplateStore().mineTemplate"
                    class="bg-gradation-top-fdcbf1-e6dee9 rounded-borders"
                    color="orange"
                    dense
                    :label="$t('template')"
                    option-label="name"
                    option-value="item"
                    popup-content-class="bg-gradation-to-top-9890e3-b1f4cf"
                    standout
                    style="width: 150px"
                    transition-hide="scale"
                    transition-show="scale"
                  >
                    <template v-slot:option="scope">
                      <q-item v-bind="scope.itemProps">
                        <q-item-section avatar>
                          {{ scope.opt.data.name }}
                        </q-item-section>
                        <q-item-section>
                          <q-item-label
                            >{{ $t('templateComponent') }}:{{
                              scope.opt.data.componentName
                            }}
                          </q-item-label>
                          <q-item-label caption
                            >id:{{ scope.opt.data.id }}
                          </q-item-label>
                        </q-item-section>
                      </q-item>
                    </template>
                  </q-select>
                </q-item-section>

                <q-item-section avatar>
                  <q-input
                    v-model="item.templateId"
                    dense
                    :label="$t('templateId')"
                    style="width: 100px"
                  />
                </q-item-section>
                <q-item-section>
                  <q-input
                    v-model="item.generatedPath"
                    dense
                    :label="$t('templateOut')"
                    style="width: 300px"
                  >
                    <template v-slot:after>
                      <q-toggle
                        v-model="item.postfix"
                        :icon="item.postfix ? 'merge' : 'merge_type'"
                        color="green"
                      >
                        <q-tooltip
                          delay="700"
                          :offset="[10, 10]"
                          class="bg-amber text-black shadow-4"
                        >
                          {{
                            item.postfix
                              ? $t('templateSuffixOn')
                              : $t('templateSuffixOff')
                          }}
                        </q-tooltip>
                      </q-toggle>
                      <q-btn
                        class="q-ml-sm text-white bg-gradation-120deg-f093fb-f5576c"
                        dense
                        icon="delete"
                        size="sm"
                        @click="
                          useProjectStore().project.mapper.splice(index, 1)
                        "
                      >
                        <q-tooltip
                          delay="700"
                          :offset="[10, 10]"
                          class="bg-grey-3 text-cyan text-bold"
                          >{{$t('delete')}}
                        </q-tooltip>
                      </q-btn>
                    </template>
                  </q-input>
                </q-item-section>
              </q-item>
            </q-list>
          </q-list>
        </q-tab-panel>
        <q-tab-panel class="q-pa-none" name="C6">
          <q-list>
            <!--            -->

            <q-item>
              <q-item-section avatar>
                <q-input
                  v-model="useConfigStore().config.configFilePath"
                  dense
                  :label="$t('confFilePath')"
                  style="width: 500px"
                >
                  <template v-slot:append>
                    <q-btn
                      dense
                      flat
                      icon-right="folder"
                      @click="
                        selectFolder(
                          'useProjectStore().configFilePath',
                          configStore.configFilePath
                        )
                      "
                    >
                    </q-btn>
                  </template>
                </q-input>
              </q-item-section>
            </q-item>
            <!--            -->

            <q-item>
              <q-item-section avatar>
                <q-input
                  v-model="useConfigStore().config.templateFilePath"
                  dense
                  :label="$t('templateFilePath')"
                  style="width: 500px"
                >
                  <template v-slot:append>
                    <q-btn
                      dense
                      flat
                      icon="folder"
                      @click="
                        selectFolder(
                          'useProjectStore().templateFilePath',
                          configStore.templateFilePath
                        )
                      "
                    >
                      <q-tooltip delay="700">{{
                        $t('selectFilePath')
                      }}</q-tooltip>
                    </q-btn>
                    <q-btn
                      dense
                      flat
                      icon="folder_open"
                      @click="
                        openFolder(
                          $t('openFilePath'),
                          configStore.templateFilePath
                        )
                      "
                    >
                      <q-tooltip delay="700">{{
                        $t('openFilePath')
                      }}</q-tooltip>
                    </q-btn>
                  </template>
                </q-input>
              </q-item-section>
            </q-item>

            <q-item>
              <q-item-section avatar>
                <q-select
                  v-model="useConfigStore().config.projectName"
                  :options="useConfigStore().config.projects"
                  dense
                  :label="$t('projectConfig')"
                  style="width: 200px"
                />
              </q-item-section>
            </q-item>

            <q-item>
              <q-item-section avatar>
                <q-select
                  v-model="locale"
                  :options="localeOptions"
                  :label="$t('language')"
                  dense
                  borderless
                  emit-value
                  map-options
                  options-dense
                  style="min-width: 150px"
                />
              </q-item-section>
            </q-item>

            <q-separator />
          </q-list>
        </q-tab-panel>
      </q-tab-panels>
    </q-card>
  </div>
  <q-dialog v-model="addProjectDlgShow" persistent>
    <q-card>
      <q-card-actions class="dyh"> {{ $t('addProject') }}</q-card-actions>
      <q-separator />
      <q-list padding>
        <q-item class="flex justify-center items-center">
          <q-item-label class="text-weight-thin dyh text-body1 text-grey-7"
            >{{ $t('projectName') }}：
          </q-item-label>
          <q-input v-model="newProjectFrom.name" class="q-mx-md" dense filled />
        </q-item>
        <q-item class="flex justify-end items-center text-grey-7">
          <q-item-label class="text-weight-thin dyh text-body1"
            >projectAuthor：
          </q-item-label>
          <q-input
            v-model="newProjectFrom.author"
            class="q-mx-md"
            dense
            filled
          />
        </q-item>
        <div
          class="text-weight-thin dyh text-body1 q-px-xs full-width flex justify-end items-center"
        >
          <q-btn
            class="q-ma-xs full-width"
            color="green-4"
            dense
            :label="$t('create')"
            @click="
              () => {
                addProjectDlgShow = false;

                addProject();
              }
            "
          />
          <q-btn
            class="q-ma-xs full-width"
            color="red-4"
            dense
            :label="$t('cancel')"
            @click="addProjectDlgShow = false"
          />
        </div>
      </q-list>
    </q-card>
  </q-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, toRaw, watch } from 'vue';
import { Ref } from 'vue/dist/vue';
import { getFilePathTree, isFile, pathJoin } from 'src/api/SysApi';
import QlEditor from 'components/QlEditor.vue';
import { initDatabaseConnection, showTables } from 'src/api/DatabaseApi';
import { LocalStorage, Notify } from 'quasar';
import { useConfigStore } from 'stores/configStore';
import { useProjectStore } from 'stores/projectStore';
import { EmptyObject } from 'src/stores';
import { mineTemplateStore } from 'stores/mineTemplateStore';
import {
  cmsDatasourceConfig,
  deleteCmsDatasourceConfig,
  send2Id,
} from 'src/api/api';
import { useUserStore } from 'stores/userStore';
import { useI18n } from 'vue-i18n';

const isPwd = ref(true);
const isHost = ref(true);
const fileNodes = ref(
  [] as { label: string; lazy: boolean; value: string; children?: [] }[]
);

const { locale, t } = useI18n({ useScope: 'global' });
const localeOptions = [
  { value: 'zh-CN', label: '中文' },
  { value: 'en-US', label: 'English' },
  { value: 'ja', label: '日本語' },
  { value: 'de', label: 'Das ist Deutsch' },
  { value: 'ru', label: 'русск' },
  { value: 'ko', label: '한국어' },
  { value: 'it', label: 'italia' },
  { value: 'fr', label: 'français' },
];
const mineTemplateList = ref([] as EmptyObject[]);
const addProjectDlgShow = ref(false);
const newProjectFrom = ref({ name: '', author: '' });
const addProject = async () => {
  useConfigStore().config.projectName = newProjectFrom.value.name;
  useConfigStore().config.projects?.push(newProjectFrom.value.name);
  console.log(useConfigStore().config.projects);
  await useConfigStore().refresh(useConfigStore().config);
  await useProjectStore().getProject();
  console.log('addProject', useProjectStore().project);
  newProjectFrom.value = {
    name: '',
    author: '',
  };
};
const addProjectDlg = () => {
  addProjectDlgShow.value = true;
};
const templateId = ref(0);
const updateEditor = (id: number) => {
  templateId.value = id;
};
const schemaTableList: Ref<
  { name: string; nickName: string; value: number }[]
> = ref([]);
const initSchemaTable = async () => {
  await initDatabaseConnection(
    toRaw(useProjectStore().project.datasource[check.value])
  ).then(() => {
    showTables().then((res) => {
      console.log(res.results);
      res?.results?.forEach((i, index) => {
        schemaTableList.value.push({
          name: i.TABLE_NAME,
          nickName: i.TABLE_COMMENT,
          value: index,
        });
      });
    });
  });
};
const addDatabaseConfig = () => {
  useProjectStore().project.datasource.push({
    host: '',
    nickname: '',
    username: '',
    password: '',
    database: '',
    type: 'mysql',
    port: 3306,
    save: '',
    global: false,
    selected: true,
  });
  check.value = useProjectStore().project.datasource?.length - 1;
};

const tab = ref('c1');
const check = ref(0);
const splitterModel = ref(18);
watch(check, () => {
  console.log(check.value);
});
watch(locale, () => {
  LocalStorage.set('locale', locale.value);
});
const uploadDatabase = async (index: number) => {
  console.log(index);
  let redId = (
    await cmsDatasourceConfig(
      toRaw(useProjectStore().project.datasource[index])
    )
  ).data.data;
  if (redId) {
    useProjectStore().project.datasource[index].id = redId;
    Notify.create({
      message: t('success'),
      position: 'top-right',
      type: 'info',
    });
    await send2Id({
      id: [...(useUserStore().user.id + '')],
      msg: JSON.stringify({
        code: 3,
        content: 'win',
      }),
    });
  } else {
    Notify.create({
      message: t('bad'),
      position: 'top-right',
      type: 'red',
    });
  }
};
const unUploadDatabase = async (index: number) => {
  console.log(index);
  if (
    (
      await deleteCmsDatasourceConfig(
        useProjectStore().project.datasource[index].id
      )
    ).data.data
  ) {
    useProjectStore().project.datasource[index].id = null;
    Notify.create({
      message: t('success'),
      position: 'top-right',
      type: 'info',
    });
    await send2Id({
      id: [...(useUserStore().user.id + '')],
      msg: JSON.stringify({
        code: 3,
        content: 'win',
      }),
    });
  } else {
    Notify.create({
      message: t('bad'),
      position: 'top-right',
      type: 'red',
    });
  }
};
const getFileTree = (path: string) => {
  getFilePathTree(path).then(async (res) => {
    console.log(res);
    let node = [];
    for (const i of res) {
      node.push({
        label: i,
        value: pathJoin(path, i),
        lazy: (await isFile(pathJoin(path, i))) as boolean,
      });
    }
    fileNodes.value = node;
  });
};
const selectFolder = (value: string, path?: string) => {
  window.ipcCom
    .selectFolder(t('openFilePath'), path || window.ipcCom.getDirname())
    .then((path) => {
      console.log(path);
      if (path) eval(value + ' = path');
    });
};
const openFolder = async (title: string, path: string) => {
  await window.ipcCom.openFolder(title, path);
};
const test = async () => {
  console.log(await useConfigStore().getConfig());
};
const initConfigAndDB = async () => {
  if (useProjectStore().project?.datasource?.length) {
    check.value = useProjectStore().project.datasource?.findIndex(
      (i) => i.selected === true
    );
    await initSchemaTable();
  }
};
onMounted(async () => {
  await initConfigAndDB();
  mineTemplateStore().getMineTemplateStore();
  templateId.value = mineTemplateStore().mineTemplate[0].templateId;
});
const testConnection = async () => {
  await initDatabaseConnection(
    useProjectStore().project.datasource[check.value]
  ).then(() => {
    showTables().then((res) => {
      Notify.create({
        type: res ? 'success' : 'error',
        message: res ? t('success') : t('bad'),
        position: 'top',
      });
    });
  });
};
</script>

<style lang="sass" scoped>
.q-tabs--dense
  min-height: 0
</style>
<style scoped></style>
